package com.bidevalution.business.impl;

import com.alibaba.dubbo.common.json.JSON;
import com.bidevalution.business.service.BeSectionExpertProgressService;
import com.bidevalution.business.service.BeSectionStepJobService;
import com.bidevalution.business.service.BeSectionWarnMsgService;
import com.bidevalution.business.vo.CheckJobVo;
import com.bidevalution.dao.entity.*;
import com.bidevalution.dao.enums.CheckMsgTypeEnum;
import com.bidevalution.dao.mapper.*;
import com.bidevalution.support.context.Constants;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.GsonUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 消息提醒service层
 * Created by glodon on 2020-02-18.
 */
@Log4j2
@Service
public class BeSectionWarnMsgServiceImpl implements BeSectionWarnMsgService {

    @Autowired
    private BeSectionWarnMsgMapper beSectionWarnMsgMapper;

    @Autowired
    private BeSectionExpertProgressMapper beSectionExpertProgressMapper;

    @Autowired
    private BeSectionMethodMapper beSectionMethodMapper;

    @Autowired
    private BeSectionStepJobService beSectionStepJobService;

    @Autowired
    private BeSectionExpertProgressService beSectionExpertProgressService;

    @Autowired
    private BeSectionStepMapper beSectionStepMapper;

    @Autowired
    private BeSectionInfoMapper beSectionInfoMapper;

    @Override
    public BeSectionWarnMsg getBeSectionWarnMsg(String seqId) throws Exception {
        return beSectionWarnMsgMapper.selectByPrimaryKey(seqId);
    }

    /**
     * 获取消息提醒列表信息
     * @param sectionStepId
     * @param expertId
     * @return
     */
    @Override
    public List<BeSectionWarnMsg> getUntreatedWarnMsgList(String sectionStepId, String expertId) throws Exception {
        return beSectionWarnMsgMapper.getBeSBeSectionWarnMsgList(sectionStepId, Constants.Untreated, expertId);
    }

    /**
     * 插入消息提醒信息
     * @param beSectionWarnMsg
     * @return
     */
    @Override
    public int insertWarMsg(BeSectionWarnMsg beSectionWarnMsg) throws Exception {
        beSectionWarnMsg.setSeqId(UUID.randomUUID().toString());
        return beSectionWarnMsgMapper.insert(beSectionWarnMsg);
    }

    /**
     * 处理消息提醒信息
     * @param seqId 环节id
     * @param expertId 专家id
     * @param remark 回执说明
     * @return
     */
    @Override
    @Transactional
    public void handleWarnMsg(String seqId, String expertId, String remark) throws Exception {
        BeSectionWarnMsg beSectionWarnMsg = beSectionWarnMsgMapper.selectByPrimaryKey(seqId);
        if (beSectionWarnMsg == null) {
            throw new Exception("没有找到消息提醒信息");
        }

        String sectionStepId = beSectionWarnMsg.getSectionStepId();
        List<BeSectionWarnMsg> allList = beSectionWarnMsgMapper.getBeSBeSectionWarnMsgList(sectionStepId, Constants.Untreated, null);

        beSectionWarnMsg.setRemark(remark);
        beSectionWarnMsg.setStatus(Constants.Treated);
        beSectionWarnMsg.setUpdateTime(DateUtil.now());
        //处理消息提醒状态
        beSectionWarnMsgMapper.handleWarnMsg(beSectionWarnMsg);

        //TODO 这里转换有扩展局限性，最好扩展个字段,暂时够用
        CheckJobVo vo  = JSON.parse(beSectionWarnMsg.getMsgDetails(), CheckJobVo.class);
        boolean isFirst = allList.size() == vo.getExperTotal() ? true : false;
        // 重置
        if (!CheckMsgTypeEnum.None.equals(beSectionWarnMsg.getMsgTypeEnum()) && isFirst) {
            log.info("=========发起重置==============:"+sectionStepId+" msg: "+beSectionWarnMsg.getMsgDetails());
            //更新专家提交状态
            resetUnFinishState(new ArrayList<>(vo.getFailureMap().keySet()), sectionStepId);
        }

    }

    private void resetUnFinishState(List<String> experts, String beSectionStepId) throws Exception {
        log.info("LOG[]resetUnFinishState[]{},params={}", "记录日志",GsonUtil.toJsonWithGson(experts)+";"+GsonUtil.toJsonWithGson(beSectionStepId));
        BeSectionStep beSectionStep = beSectionStepMapper.selectByPrimaryKey(beSectionStepId);
        List<BeSectionStep> childSectionStep= beSectionStepMapper.getAllChildSectionStep(beSectionStep.getSectionId(), beSectionStep.getStepCode());
        for (String expertId : experts) {
            //更新当前所有子节点环节完成状态
            BeSectionExpertProgress beSectionExpertProgress = beSectionExpertProgressService
                    .selectByKey(beSectionStep.getSeqId(), expertId);
            beSectionExpertProgress.setIsFinish(Constants.IS_FINISH);
            beSectionExpertProgressService.update(beSectionExpertProgress);
            //更新任务状态
            beSectionStepJobService.updateStepJobByStepId(beSectionStepId, Constants.IS_FINISH);
            // 更新子任务
            for (BeSectionStep sectionStep : childSectionStep) {
                beSectionExpertProgress = beSectionExpertProgressService.selectByKey(sectionStep.getSeqId(), expertId);
                beSectionExpertProgress.setIsFinish(Constants.IS_FINISH);
                beSectionExpertProgressService.update(beSectionExpertProgress);
                //更新任务状态
                beSectionStepJobService.updateStepJobByStepId(sectionStep.getSeqId(), Constants.IS_FINISH);
            }
        }
        BeSectionInfo sectionInfo = new BeSectionInfo();
        sectionInfo.setSeqId(beSectionStep.getSectionId());
        //评审中
        sectionInfo.setReviewState(2);
        beSectionInfoMapper.updateByPrimaryKeySelective(sectionInfo);
    }

    /**
     * 获取专家打分异常的企业信息
     * @param sectionStepId
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public List<ExpertWarnMsgVo> getExpertWarnMsgDetail(String sectionStepId, String sectionId) throws Exception {
        BeSectionMethod beSectionMethod = beSectionMethodMapper.selectByPrimaryKey(sectionId);
        if (beSectionMethod == null) {
            throw new Exception("该标段未查询到评标方法相关信息！");
        }
        return beSectionWarnMsgMapper.getExpertWarnMsg(sectionStepId,sectionId,beSectionMethod.getSubmitCode());
    }

    /**
     * 根据环节id更新处理状态
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public void invalidAll(String sectionId) throws Exception {
        BeSectionWarnMsg beSectionWarnMsg = new BeSectionWarnMsg();
        beSectionWarnMsg.setSectionId(sectionId);
        beSectionWarnMsg.setStatus(Constants.Invalid);
        beSectionWarnMsg.setUpdateTime(DateUtil.now());
        //处理消息提醒状态
        beSectionWarnMsgMapper.updateStatus(beSectionWarnMsg);
    }

    @Override
    public List<BeSectionWarnMsg> getMsgByRemark(String sectionId, String remark) throws Exception {
        log.info("LOG[]getMsgByRemark[]{},params={}", "获取标段下有特殊备注的消息信息", GsonUtil.toJsonWithGson(sectionId)+";"+GsonUtil.toJsonWithGson(remark));
        try {
            return beSectionWarnMsgMapper.getMsgByRemark(sectionId,remark);
        }catch (Exception e){
            log.error("LOG[]getMsgByRemark[]{},error={},params={}","获取标段下有特殊备注的消息信息异常",GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(sectionId)+";"+GsonUtil.toJsonWithGson(remark));
            return new ArrayList<>();
        }
    }

    @Override
    public void overdueMag(String sectionStepId) {
        beSectionWarnMsgMapper.overdueMag(sectionStepId);
}
}
